package com.browsesoft.baseadapter;

import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import oracle.sql.BLOB;

import com.browsesoft.SequenceFind;
import com.browsesoft.dbtools.ConnectionPool;
import com.browsesoft.dbtools.DBTools;
import com.browsesoft.util.StreamHelper;

/**
 * 负责存贮oracle的lob字段 使用是先取得输出流，写入，然后调用save方法
 * 
 * @author not attributable
 * @version 1.0
 */
public class OracleBLobEntity implements BlobEntity {
	/**
	 * 
	 */
	private static final long serialVersionUID = 4539263207621398799L;

	// id
	private String id;

	// BLOB对象
	private BLOB blob;

	private OutputStream outStream = null;

	private Connection connection = null;

	private static String tableName = "t_blob_entity";

	/**
	 * 根据id号从数据库中找到blob对象
	 * 
	 * @param id
	 * @throws BLobObjectNotFoundException
	 */
	public OracleBLobEntity(String id) throws BLobObjectNotFoundException {
		try {
			this.blob = getBlob(id);
			this.outStream = this.blob.getBinaryOutputStream();
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * @param id
	 * @throws BLobObjectNotFoundException
	 */
	private BLOB getBlob(String id) throws BLobObjectNotFoundException {
		Statement st = null;
		ResultSet rs = null;
		try {
			connection = ConnectionPool.createTempConnection();
			connection.setAutoCommit(false);
			st = connection.createStatement();
			String sql = " select content from t_blob_entity where id='" + id
					+ "' for update";
			rs = st.executeQuery(sql);
			if (!rs.next()) {
				throw new BLobObjectNotFoundException();
			}
			blob = (BLOB) rs.getBlob(1);
			return blob;
		} catch (SQLException ex) {
			throw new RuntimeException(ex);
		} finally {
			if (rs != null) {
				try {
					rs.close();
				} catch (SQLException e) {
				}
			}
			if (st != null) {
				try {
					st.close();
				} catch (SQLException e) {
				}
			}
		}
	}

	public OracleBLobEntity() {
		try {
			id = Integer.toString(SequenceFind.getID());
			String sql = "insert into " + tableName + " values('" + id
					+ "',empty_blob())";
			DBTools.excuteUpdate(sql);
			this.blob = this.getBlob(id);
			this.outStream = this.blob.getBinaryOutputStream();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.browsesoft.baseadapter.BlobEntity#save()
	 */
	public void save() throws java.lang.Exception {
		outStream.flush();
		connection.commit();
		try {
			connection.close();
		} catch (SQLException e) {
		}
		outStream.close();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.browsesoft.baseadapter.BlobEntity#delete()
	 */
	public void delete() throws java.lang.Exception {
		// 从数据库中删除
		DBTools.delete(tableName, id);
	}

	/**
	 * 更新内容
	 * 
	 */
	public void saveOrUpdate(byte[] fileBody) {
		try {
			this.outStream = this.getOutputStream();
			this.outStream.write(fileBody);
			this.save();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.browsesoft.baseadapter.BlobEntity#getOutputStream()
	 */
	public OutputStream getOutputStream() throws Exception {
		return outStream;
	}

	// public void createFile(String path) throws Exception {
	// File f = new File(path);
	// if (!f.exists()) {
	// f.createNewFile();
	// InputStream is = this.getInputStream();
	// OutputStream os = new FileOutputStream(f);
	// byte[] b = new byte[1024];
	// int len = is.read(b);
	// while (len != -1) {
	// os.write(b, 0, len);
	// len = is.read(b);
	// }
	// os.flush();
	// os.close();
	// is.close();
	// }
	// }

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.browsesoft.baseadapter.BlobEntity#getInputStream()
	 */
	public InputStream getInputStream() throws Exception {
		return blob.getBinaryStream();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.browsesoft.baseadapter.BlobEntity#getContent()
	 */
	public String getContent() {
		try {
			InputStream is = this.getInputStream();
			// 读取内容
			String result = StreamHelper.getString(is);
			is.close();
			return result;
		} catch (Exception ex) {
			throw new RuntimeException("读取大字断内容时失败", ex);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.browsesoft.baseadapter.BlobEntity#getID()
	 */
	public String getID() {
		return this.id;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.browsesoft.baseadapter.BlobEntity#close()
	 */
	public void close() {
		try {
			connection.commit();
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
		try {
			connection.close();
		} catch (SQLException e) {
		}
	}

	/*
	 * 
	 */
	/*
	 * (non-Javadoc)
	 * 
	 * @see com.browsesoft.baseadapter.BlobEntity#getLength()
	 */
	public long getLength() {
		try {
			return blob.length();
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
}
